package com.hskn.hss.module.maintaincfg.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hskn.hss.core.annotation.SysLog;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.enums.BusinessType;
import com.hskn.hss.core.utils.file.FileTypeUtils;
import com.hskn.hss.core.utils.poi.ExcelUtil;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.ExcelReaderDataException;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.common.ienum.ExcelTypeEnum;
import com.hskn.hss.module.common.to.ExcelReaderTO;
import com.hskn.hss.module.costdictitem.entity.CostDictItem;
import com.hskn.hss.module.costdictitem.service.ICostDictItemService;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.insuranceCfg.entity.TlInsuranceCfg;
import com.hskn.hss.module.jobset.mapper.JobsetMapper;
import com.hskn.hss.module.maintaincfg.entity.TlMaintainCfg;
import com.hskn.hss.module.maintaincfg.mapper.TlMaintainCfgMapper;
import com.hskn.hss.module.maintaincfg.service.ITlMaintainCfgService;
import com.hskn.hss.module.maintaincfg.to.TlMaintainCfgListTO;
import com.hskn.hss.module.maintaincfg.vo.TlMaintainCfgExcelInVO;
import com.hskn.hss.module.maintaincfg.vo.TlMaintainCfgExcelOutVO;
import com.hskn.hss.module.tlcar.entity.TlCar;
import com.hskn.hss.module.tlcar.service.ITlCarService;
import com.hskn.hss.module.tlcartype.entity.TlCarType;
import com.hskn.hss.module.tlcartype.mapper.TlCarTypeMapper;
import com.hskn.hss.module.tlcartype.service.ITlCarTypeService;
import com.hskn.hss.module.tlcartype.service.impl.TlCarTypeServiceImpl;
import com.hskn.hss.to.ForIdsTO;
import com.hskn.hss.utils.StringUtils;
import com.hskn.hss.utils.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hskn
 * @since 2021-05-06
 */
@Slf4j
@RestController
@RequestMapping("/hss/tlmaintaincfg")
@Api(tags = {"-tl_maintain_cfg"}, description = "车辆保养费")
public class TlMaintainCfgController {
    @Resource
    private ITlMaintainCfgService tlMaintainCfgService;
    @Autowired
    private ISysDepartService departService;
    @Resource
    private ICostDictItemService costDictItemService;
    @Resource
    private ITlCarService carService;
    @Resource
    private ITlCarTypeService tlCarTypeService;
    /***
     * 新增
     * @param request
     * @return
     */
    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_maintain_cfg", bean = TlMaintainCfg.class, beanMapper = TlMaintainCfgMapper.class, names = "carnumid")
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public AjaxResult<Object> insert(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            return tlMaintainCfgService.insert(params);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    /**
     * 修改
     *
     * @param request
     * @return
     */
    @SysLog(businessType = BusinessType.UPDATE, tableName = "tl_maintain_cfg", idKey = "id", bean = TlMaintainCfg.class, beanMapper = TlMaintainCfgMapper.class, names = "carnumid")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public AjaxResult<Object> update(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            return tlMaintainCfgService.update(params);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    /***
     * 删除
     * @param forIdsTO
     * @return
     */
    @SysLog(businessType = BusinessType.DELETE, tableName = "tl_maintain_cfg", idKey = "ids", bean = TlMaintainCfg.class, beanMapper = TlMaintainCfgMapper.class, names = "carnumid")
    @RequestMapping(value = "deleteByid", method = RequestMethod.POST)
    public AjaxResult<Object> deleteByid(@RequestBody @Validated ForIdsTO forIdsTO) {
        try {
            return tlMaintainCfgService.deleteByid(forIdsTO);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("删除失败，请稍后再试");
        }
    }

    /**
     * 根据Id获取
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getbyid", method = RequestMethod.POST)
    public AjaxResult<Object> getbyid(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        TlMaintainCfg tlMaintainCfg = null;
        try {
            tlMaintainCfg = tlMaintainCfgService.getDetailById(params);
            return AjaxResult.success(tlMaintainCfg);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }


    }

    /**
     * 获取列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getlist", method = RequestMethod.POST)
    public AjaxResult<Object> getlist(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        try {
            BaseEntity entity = new BaseEntity();
            JSONObject json = tlMaintainCfgService.getList(entity ,params);
            return AjaxResult.success(json);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }

    }
    /**
     * 车辆保养费导入接口
     *
     * @param request
     * @return
     */
//    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_maintain_cfg", bean = TlMaintainCfg.class, beanMapper = TlMaintainCfgMapper.class, names = "carnumid")
    @ApiOperation(value = "车辆保养费导入接口", notes = "车辆保养费导入")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @PostMapping("excelReader")
    public AjaxResult excelReader(HttpServletRequest request,@ModelAttribute   @Validated ExcelReaderTO excelReaderTo) {
        try {
            MultipartFile file=excelReaderTo.getFiles();
            if(Arrays.stream(ExcelTypeEnum.values()).noneMatch(s->s.getName().equals(FileTypeUtils.getFileType(file.getOriginalFilename().toLowerCase())))){
                return AjaxResult.fail("导入文件格式错误");
            }
            InputStream inputStream = new BufferedInputStream(file.getInputStream());
            ExcelUtil<TlMaintainCfg> util = new ExcelUtil<TlMaintainCfg>(TlMaintainCfg.class);
            List<TlMaintainCfg> inspectionCfgList = util.importExcel(inputStream);
            if(inspectionCfgList.isEmpty()){
                return AjaxResult.fail("导入内容为空");
            }
            tlMaintainCfgService.excelReader(inspectionCfgList);
            if ( tlMaintainCfgService.saveBatch(inspectionCfgList)) {
                return AjaxResult.success();
            }else {
                return AjaxResult.fail("导入失败");
            }
        } catch (ExcelReaderDataException e) {
            return AjaxResult.fail(e.getMessage());
        }catch (Exception exception){
            exception.printStackTrace();
            return AjaxResult.fail();
        }

    }
    @ApiOperation(value = "车辆保养费导出接口", notes = "车辆保养费导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok" ,response = TlMaintainCfgExcelOutVO.class)
    })
    @PostMapping("excelExport")
    public com.hskn.hss.core.domain.AjaxResult excelExport(HttpServletRequest request,@RequestBody TlMaintainCfgListTO inspectionCfgListTo) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if((inspectionCfgListTo.getIds()!=null&&inspectionCfgListTo.getIds().isEmpty())){
                return com.hskn.hss.core.domain.AjaxResult.error("请选择至少一条数据导出");
            }
            //查询数据
            List<TlMaintainCfg> inspectionCfgList = tlMaintainCfgService.getMaintainCfgList(inspectionCfgListTo, format);
            //工具类实例化
            ExcelUtil<TlMaintainCfgExcelOutVO> util = new ExcelUtil<TlMaintainCfgExcelOutVO>(TlMaintainCfgExcelOutVO.class);
            //数据载体转换
            List<TlMaintainCfgExcelOutVO> inspectionCfgExcelOutVOList=JSONObject.parseArray(JSONObject.toJSONString(inspectionCfgList),TlMaintainCfgExcelOutVO.class);
            //构造结果集
            Map<String, SysDepart> departMap=departService.getDepartMap(new QueryWrapper<>());
            Map<String, CostDictItem> costDictItemMap=costDictItemService.getCostDictItemMap(new QueryWrapper<>());
            Map<String, TlCar> carMap=carService.getCarMap(new QueryWrapper<>());
            Map<String, TlCarType> carTypeMap=tlCarTypeService.getCarTypeMap(new QueryWrapper<>());
            for(TlMaintainCfgExcelOutVO inspectionCfgExcelOutVO:inspectionCfgExcelOutVOList){
                if(departMap.containsKey(inspectionCfgExcelOutVO.getDeptid())){
                    inspectionCfgExcelOutVO.setDeptName(departMap.get(inspectionCfgExcelOutVO.getDeptid()).getDepartName());
                }
                if(costDictItemMap.containsKey(inspectionCfgExcelOutVO.getRepairreason())){
                    inspectionCfgExcelOutVO.setRepairreasonName(costDictItemMap.get(inspectionCfgExcelOutVO.getRepairreason()).getCostname());
                }
                if(carMap.containsKey(inspectionCfgExcelOutVO.getCarnumid())){
                    inspectionCfgExcelOutVO.setCarCardNum(carMap.get(inspectionCfgExcelOutVO.getCarnumid()).getCarnumber());
                }
                if (StringUtils.isNotEmpty(inspectionCfgExcelOutVO.getCosttime())) {
                    inspectionCfgExcelOutVO.setCosttimeString(format.format(inspectionCfgExcelOutVO.getCosttime()));
                }
                if(StringUtils.isNotEmpty(inspectionCfgExcelOutVO.getCartype())){
                    inspectionCfgExcelOutVO.setCartypeName(carTypeMap.get(inspectionCfgExcelOutVO.getCartype()).getTypename());
                }
            }
            //            导出
            return util.exportExcel(inspectionCfgExcelOutVOList,"车辆保养");

        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }



    @ApiOperation(value = "车辆保养费导出模板接口", notes = "车辆保养费模板导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok" ,response = TlMaintainCfgExcelInVO.class)
    })
    @PostMapping("excelExportTemplate")
    public com.hskn.hss.core.domain.AjaxResult excelExportTemplate(HttpServletRequest request) {
        try {
            //工具类实例化
            ExcelUtil<TlMaintainCfgExcelInVO> util = new ExcelUtil<TlMaintainCfgExcelInVO>(TlMaintainCfgExcelInVO.class);
            //数据载体转换
            List<TlMaintainCfgExcelInVO> inspectionCfgExcelOutVOList=new ArrayList<>();
            //导出
            return util.exportExcel(inspectionCfgExcelOutVOList,"车辆保养模板");
        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }
}

